import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Modal } from 'antd';
import { getAllCity } from '@/services/auth';
import { addCityThirdParty, updateCityThirdParty } from '@/services/city';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { connect } from 'dva';
import { to } from '@/utils/smallTool';
import authUtil from '@/utils/auth';
import styles from './index.less';
import City from './City';
import Business from './Business';
import Reptile from './Reptile';
import ThirdParty from './ThirdParty';
import dataConfig from './config-data';

const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 };
const drawerWidth = '55%';
@connect(({ global, loading, city, authority }) => ({
  tableData: city.tableData,
  searchForm: city.searchForm,
  permissionsList: authority.permissionsList,
  tableLoading: loading.effects['city/getCityByPage'],
  watermarkConfig: global.watermarkConfig,
}))
class CityConfig extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      drawerStatus: {
        city: {
          visible: false,
        },
        business: {
          visible: false,
        },
        reptile: {
          visible: false,
        },
        thirdParty: {
          visible: false,
        }
      },
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
      },
      inputConfig: [
        {
          type: 'select',
          optionData: [],
          placeholder: '请选择城市',
          name: 'userName',
          label: '城市',
          nameFiled: 'cityName',
          valueFiled: 'cityCode',
          selectProps: {
            allowClear: true,
            optionFilterProp: 'children',
            showSearch: true
          }
        }
      ]
    };
    this.$drawerForm = React.createRef();
    const { pageRequest, params } = this.state;
    this.getSelectList().then(data => {
      this.getQueryList(params, pageRequest)
    });
  }
  pulldownRefreshList(params) {
    this.setState({
      params: params,
    });
    this.getQueryList(params, { pageNum: 1, pageSize: 10 });
  }
  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    let params = formData;
    let tempDate = params.createTimeStart;
    if (isClear) {
      // 重置表单
      params = {
        createTimeStart: dateStartTime,
        createTimeEnd: authUtil.getCurrentEedDateTime()
      }
    } else if (tempDate && tempDate.length) {
      params.createTimeStart = authUtil.getStartDateTime(new Date(tempDate[0]).getTime());
      params.createTimeEnd = tempDate[1] ? authUtil.getCurrentEedDateTime(new Date(tempDate[1]).getTime()) : authUtil.getCurrentEedDateTime()
    } else {
      params.createTimeStart = params.createTimeEnd = ''
    }
    this.pulldownRefreshList(params);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'city/getCityByPage';
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: { ...params, ...pageRequest },
    });
  };

  /**
   * @description 请求事件类型下拉列表数据
   * @author zhe
   * @date 2020-04-14
   * @memberof
   */
  getSelectList = async () => {
    const { inputConfig } = this.state;
    const dataObj = await getAllCity();
    let baseIndex = 8;
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data !== null) {
        inputConfig[0].optionData = dataObj.data;
        this.setState({ inputConfig: inputConfig });
      }
    }
    return;
  };

  /**
   * @description table操作触发改变事件
   * @author songs
   * @date 2019-07-12
   * @param {*} pagination
   * @param {*} filtersArg
   * @param {*} sorter
   * @memberof managementUser
   */
  handleStandardTableChange = (pagination, filtersArg, sorter, actionType) => {
    const { pageSize, current } = pagination;
    const pageRequest = { pageSize, pageNum: current };
    this.getQueryList(filtersArg, pageRequest);
  };
  onDrawerOk(type) {
    this.setDrawerStatus(type, false);
  }
  async saveThirdPartyConfig(data) {
    let responseData, postRes = false;
    if (data.id) {
      responseData = await updateCityThirdParty(data);
    } else {
      responseData = await addCityThirdParty(data);
    }
    if (responseData && responseData.code === '000000') {
      postRes = true;
    }
    return postRes;
  }
  // 保存城市第三方配置信息
  async handleSaveThirdParyConfig() {
    const { validateFields } = this.$drawerForm.current.props.form;
    let [validateError, validateRes] = await to(validateFields());
    if (validateError) return false;
    let postRes = await this.saveThirdPartyConfig(validateRes)
    if (postRes) {
      this.changeDrawerStatus(false, 'thirdParty')
    }
  }
  setDrawerStatus(type, visible, activeRecord) {
    this.setState(oldState => ({
      ...oldState,
      drawerStatus: { ...oldState.drawerStatus, [`${type}`]: { visible } },
      activeRecord
    }));
  }
  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} text
   * @param {*} title
   */
  changeDrawerStatus = (visible, text = '', activeRecord = {}, event) => {
    const config = {
      '城市参数': 'city',
      '业务参数': 'business',
      '基数/比例参数': 'reptile',
      '城市抓取配置': 'thirdParty',
    }
    const type = config[text] || text;
    this.setDrawerStatus(type, visible, activeRecord);
  };
  tableCol = () => {
    const { tableData } = this.props;
    const { pagination = {} } = tableData;
    const { pageSize = 50, current = 0 } = pagination;
    const { configData } = this.state;
    const OptionNode = ({ id, index, record, text }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          onClick={() => {
            this.changeDrawerStatus(true, text, record);
          }}
        >
          {text}
        </Button>
      </div>
    );
    return dataConfig.getTableConfig(OptionNode)
  };
  render() {
    const { tableCol } = this;
    const { inputConfig, drawerStatus, activeRecord } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <div style={{ marginBottom: '10px', height: '32px', lineHeight: '32px' }}>实名认证明细分页查询</div>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => index}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'city/getCityByPage');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title='城市参数维护'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={() => this.changeDrawerStatus(false, 'city')}
          footer={<Button type="primary" onClick={() => this.changeDrawerStatus(false, 'city')
          }>关闭</Button>}
          visible={drawerStatus['city'].visible}
        >
          <City record={activeRecord}></City>
        </Modal>
        <Modal
          title='业务参数维护'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={() => this.changeDrawerStatus(false, 'business')}
          footer={<Button type="primary" onClick={() => this.changeDrawerStatus(false, 'business')
          }>关闭</Button>}
          visible={drawerStatus['business'].visible}
        >
          <Business record={activeRecord}></Business>
        </Modal>
        <Modal
          title='城市抓取配置'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={() => this.changeDrawerStatus(false, 'reptile')}
          footer={<Button type="primary" onClick={() => this.changeDrawerStatus(false, 'reptile')
          }>关闭</Button>}
          visible={drawerStatus['reptile'].visible}
        >
          <Reptile record={activeRecord}></Reptile>
        </Modal>
        <Modal
          title='第三方地址配置'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={() => this.changeDrawerStatus(false, 'thirdParty')}
          onOk={() => this.handleSaveThirdParyConfig()}
          visible={drawerStatus['thirdParty'].visible}
        >
          <ThirdParty record={activeRecord} $ref={this.$drawerForm}></ThirdParty>
        </Modal>
      </div >
    );
  }
}

export default CityConfig;
